# -*- coding=utf8 -*-
from django.contrib.auth import authenticate, login
import django.forms as forms
from django.contrib.auth.models import User
from django.shortcuts import redirect

class AuthenticationForm(forms.Form):
    password = forms.CharField(label=u"Пароль", widget=forms.PasswordInput)
    username = forms.CharField(label=u"Логин", max_length=30)

    error_messages = {
        "invalid_login": u"Неправильный логин или пароль!",
        "inactive": u"Этот аккаунт удалён!",
        }

    def __init__(self, *args, **kwargs):
        self.user = None
        self.next_url = "/"
        super(AuthenticationForm, self).__init__(*args, **kwargs)

    def clean_password(self):
        return self.cleaned_data.get("password")

    def clean_username(self):
        username = self.cleaned_data.get("username")
        password = self.cleaned_data.get("password")
        self.user = authenticate(username=username, password=password)
        if not self.user:
            raise forms.ValidationError(self.error_messages["invalid_login"])
        elif not self.user.is_active:
            raise forms.ValidationError(self.error_messages["inactive"])

    def login(self, request):
        login(request, self.user)
        return redirect(self.next_url)

